<template>
  <!-- element-ui级联组件 -->
  <el-cascader
    :value="value"
    size="mini"
    :options="treeData"
    :props="cascader.props"
    separator="-"
    @change="change"
  />
</template>
<script>
import { getDepartment } from '@/api/department'
export default {
  props: {
    value: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      treeData: [], // 赋值给 级联组件的options
      cascader: {
        props: {
          label: 'name', // 要展示的字段
          value: 'id', // 要存储的字段
          checkStrictly: true
        }
      }
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    change(e) {
      console.log(e)
      this.$emit('input', e[e.length - 1])
    },
    async getDepartment() {
      // 获取数据
      const res = await getDepartment()
      // console.log(res)

      // 声明一个找儿子的函数
      function getChildren(id) {
        return res.filter((v) => v.pid === id)
      }
      //
      res.forEach((v) => {
        if (getChildren(v.id).length) {
          v.children = getChildren(v.id)
        }
      })

      // 将一级节点找出来
      const list = res.filter((v) => v.pid === 0)
      // console.log(list, 'list')
      this.treeData = list
    }
  }
}
</script>
